package sundun.sharding.enums;




import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import sundun.sharding.utils.ShardingAlgorithmUtil;

import java.util.*;


/**
 *
 * 分片表缓存枚举
 * @author: zxl
 * @date: 2024/07/31 20:17
 */
@Slf4j
public enum ShardingTableCacheEnum {

    /**
     * 昨日警情表
     */
    IMS_YESTERDAT_JQXX("ims_yesterday_jqxx",ShardingRuleEnum.YEAR,  new HashSet<>()),
    /**
     * 昨日案件表
     */
    IMS_YESTERDAT_AJXX("ims_yesterday_ajxx",ShardingRuleEnum.YEAR, new HashSet<>());
      ;

    /**
     * 逻辑表名
     */
    private final String logicTableName;


    /**
     * 分片匹配规则
     */
    private final ShardingRuleEnum  ruleEnum;

    /**
     * 实际表名
     */
    private final Set<String> resultTableNamesCache;

    private static Map<String, ShardingTableCacheEnum> valueMap = new HashMap<>();

    static {
        Arrays.stream(ShardingTableCacheEnum.values()).forEach(o -> valueMap.put(o.logicTableName, o));
    }

    ShardingTableCacheEnum(String logicTableName, ShardingRuleEnum ruleEnum, Set<String> resultTableNamesCache) {
        this.logicTableName = logicTableName;
        this.ruleEnum = ruleEnum;
        this.resultTableNamesCache = resultTableNamesCache;
    }

    public static ShardingTableCacheEnum of(String value) {
        return valueMap.get(value);
    }

    public String logicTableName() {
        return logicTableName;
    }

    public Set<String> resultTableNamesCache() {
        return resultTableNamesCache;
    }

    public ShardingRuleEnum getRuleEnum() {
        return ruleEnum;
    }

    /**
     * 更新缓存、配置（原子操作）
     *
     * @param tableNameList
     */
    public void atomicUpdateCacheAndActualDataNodes(List<String> tableNameList) {
        if (CollectionUtils.isEmpty(tableNameList)) {
            return;
        }
        synchronized (resultTableNamesCache) {
            // 删除缓存
            resultTableNamesCache.clear();
            // 写入新的缓存
            resultTableNamesCache.addAll(tableNameList);
            // 动态更新配置 actualDataNodes
            ShardingAlgorithmUtil.actualDataNodesRefresh(logicTableName, tableNameList);
        }
    }

    public static Set<String> logicTableNames() {
        return valueMap.keySet();
    }

    @Override
    public String toString() {
        return "ShardingTableCacheEnum{" +
                "logicTableName='" + logicTableName + '\'' +
                ", resultTableNamesCache=" + resultTableNamesCache +
                '}';
    }
}
